package com.sdhs.analyze.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sdhs.analyze.bean.InfoGantryGbuploadViu;
import com.sdhs.analyze.bean.monitorinfo.DataTransInfo;
import com.sdhs.analyze.bean.operationdata.MinuteSum;
import com.sdhs.analyze.bean.operationdata.TradeHourSum;
import com.sdhs.analyze.common.BizConstants;
import com.sdhs.analyze.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;


@Component
public class GantryVlpTask {

    SimpleDateFormat sdfDay = new SimpleDateFormat("yyyyMMdd");
    SimpleDateFormat sdfHour = new SimpleDateFormat("HH");
    SimpleDateFormat sdfMinute = new SimpleDateFormat("HHmm");

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 牌识汇总
     * @param record
     * @throws Exception
     */
    @KafkaListener(topics = "VIU")
    public void tradeTask(String record) throws Exception {
        InfoGantryGbuploadViu infoGantryGbuploadViu = JSONObject.parseObject(record, InfoGantryGbuploadViu.class);
        /* 运营数据汇总 */
        operationDataSum(infoGantryGbuploadViu);
        /* 运行监测 */
        monitor(infoGantryGbuploadViu);
    }

    /**
     * 分钟汇总
     * @param gantryId
     * @param nowDay
     * @param nowMinute
     */
    private void minuteSum(String gantryId, String nowDay, String nowMinute) {
        /* 获取分钟数据传输量汇总 */
        //key format: gantry_sum_data_minute_camera:gantryId:yyyyMMdd:HHmm
        String minuteSumKey = BizConstants.REDIS_KEY_PRE_GANTRY_SUM_DATA_MINUTE_CAMERA + gantryId + ":" + nowDay + ":" + nowMinute;
        String jsonString = redisUtil.get(minuteSumKey);
        MinuteSum dataMinuteSum;
        if (jsonString == null) {
            dataMinuteSum = new MinuteSum(gantryId, BizConstants.ORG_TYPE_GANTRY_FRONT, nowDay, nowMinute);
        }
        else {
            dataMinuteSum = JSON.parseObject(jsonString, MinuteSum.class);
        }

        dataMinuteSum.setCnt(dataMinuteSum.getCnt() + 1);

        /* 更新缓存 */
        redisUtil.setEx(minuteSumKey, JSONObject.toJSONString(dataMinuteSum), 1, TimeUnit.HOURS);
    }

    /**
     * 小时车流量汇总
     * @param gantryId
     * @param transDay
     * @param transHour
     */
    private void hourSum(String gantryId, String transDay, String transHour) {
        /* 获取小时车流量汇总 按交易日期小时 */
        //key format: gantry_sum_trade_hour_camera:gantryId:yyyyMMdd:HH
        String hourSumKey = BizConstants.REDIS_KEY_PRE_GANTRY_SUM_TRADE_HOUR_CAMERA + gantryId + ":" + transDay + ":" + transHour;
        String jsonString = redisUtil.get(hourSumKey);
        TradeHourSum tradeHourSum;
        if (jsonString == null) {
            tradeHourSum = new TradeHourSum(gantryId, BizConstants.ORG_TYPE_GANTRY_FRONT, transDay, transHour);
        }
        else {
            tradeHourSum = JSON.parseObject(jsonString, TradeHourSum.class);
        }

        tradeHourSum.setCnt(tradeHourSum.getCnt() + 1);

        /* 更新缓存 */
        redisUtil.setEx(hourSumKey, JSONObject.toJSONString(tradeHourSum), 1, TimeUnit.DAYS);
    }

    /**
     * 运营数据汇总
     * @param infoGantryGbuploadViu
     */
    private void operationDataSum(InfoGantryGbuploadViu infoGantryGbuploadViu) {
        /* 仅汇总车头数据 */
        if(infoGantryGbuploadViu.getShootPosition() != 1) return;
        String gantryId = infoGantryGbuploadViu.getGantryId();
        /* 获取当前时间 */
        Date picTime = infoGantryGbuploadViu.getPicTime();
        /* 获取当前时间 */
        Date now = new Date();
        String nowDay = sdfDay.format(now);
        String nowMinute = sdfMinute.format(now);

        String picDay = sdfDay.format(picTime);
        String picHour = sdfHour.format(picTime);

        /* 小时汇总：仅汇总一天内数据且有效数据 */
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(calendar.DAY_OF_MONTH, -1);
        if(picTime.after(calendar.getTime()) && infoGantryGbuploadViu.getValidStatus() <= 1) {
            hourSum(gantryId, picDay, picHour);
        }

        /* 数据传输分钟汇总，仅汇总交易时间在48小时内的 */
        calendar.setTime(new Date());
        calendar.add(calendar.HOUR_OF_DAY, -48);
        if(picTime.after(calendar.getTime())) {
            /* 数据传输分钟汇总 */
            minuteSum(gantryId, nowDay, nowMinute);
        }
    }
    /**
     * 数据传输监测
     * @param infoGantryGbuploadViu
     */
    private void dataTransMonitor(InfoGantryGbuploadViu infoGantryGbuploadViu) {

        Date picTime = infoGantryGbuploadViu.getPicTime();
        String gantryId = infoGantryGbuploadViu.getGantryId();
        Date now = new Date();

        /* 获取数据情况 */
        //key format: gantry_data_trans_info:gantryId:type
        String dataTransInfoRsuKey = BizConstants.REDIS_KEY_PRE_GANTRY_DATA_TRANS_INFO_CAMERA + gantryId;
        String jsonString = redisUtil.get(dataTransInfoRsuKey);
        DataTransInfo dataTransInfo = null;
        if(jsonString == null) {
            dataTransInfo = new DataTransInfo(gantryId, BizConstants.ORG_TYPE_GANTRY_FRONT,picTime);
        }
        else {
            dataTransInfo = JSON.parseObject(jsonString, DataTransInfo.class);
        }
        Date lastTime = dataTransInfo.getLastTime();
        if(picTime.getTime()<lastTime.getTime()){
            return;
        }
        dataTransInfo.setDelay((now.getTime() - picTime.getTime())/1000);
        dataTransInfo.setLastTime(picTime);
        dataTransInfo.setLastChangeTime(now);
        /* 前抓拍单独监测 */
        if(infoGantryGbuploadViu.getShootPosition() == 1) {
            dataTransInfo.setFrontDelay((now.getTime() - picTime.getTime())/1000);
            dataTransInfo.setFrontLastTime(picTime);
            dataTransInfo.setFrontLastChangeTime(now);
        }
        /* 更新缓存 */
        redisUtil.setEx(dataTransInfoRsuKey, JSONObject.toJSONString(dataTransInfo), 365, TimeUnit.DAYS);
    }

    /**
     * 运行监测
     * @param infoGantryGbuploadViu
     */
    private void monitor(InfoGantryGbuploadViu infoGantryGbuploadViu) {

        /* 数据传输分钟汇总，仅汇总交易时间在48小时内的 */
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(calendar.HOUR_OF_DAY, -48);
        if(infoGantryGbuploadViu.getPicTime().after(calendar.getTime())) {
            dataTransMonitor(infoGantryGbuploadViu);
        }
    }
}
